import { defineConfig } from 'vite'
import dts from 'vite-plugin-dts'

import modules from './modules.json'

const entry = modules.reduce(
  (total, current) => {
    total[current.name] = current.entry
    return total
  },
  {} as Record<string, string>
)

const extMap = {
  cjs: 'js',
  es: 'mjs'
}

export default defineConfig({
  logLevel: 'error',
  plugins: [
    dts({
      include: ['src'],
      exclude: ['**/*.spec.ts'],
      tsconfigPath: './tsconfig.app.json'
    })
  ],
  build: {
    outDir: 'lib',
    minify: true,
    lib: {
      entry,
      name: 'utils',
      fileName: (format, entryName) => {
        const ext = extMap[format]

        if (entryName === 'index') {
          return `index.${ext}`
        } else if (Object.keys(entry).includes(entryName)) {
          return `${entryName}/index.${ext}`
        } else {
          return `${entryName}.${ext}`
        }
      },
      formats: ['cjs', 'es']
    },
    rollupOptions: {
      external: ['jspdf', 'html2canvas', 'lodash-unified', 'workerpool'],
      output: {
        exports: 'named',
        preserveModules: true,
        preserveModulesRoot: './src'
      }
    }
  }
})
